import { message } from 'antd';
import useGraph from "@/store/graph"
import useChat from "@/store/chat"
// import { toFromJson } from '@/utils/type-util'
import { Cell, Model } from '@antv/x6';
export const saveGraph = () => {
  const graphJson = useGraph.getState().graph?.toJSON()
  console.log(graphJson);
}
export const importGraph = (graphJson: string) => {
  let obj: Model.ToJSONData = JSON.parse(graphJson);
  let graph = useGraph.getState().graph!;
  console.log("cell count",graph.getCellCount());
  obj.cells.forEach(cell => {
    let cell1 = new Cell(cell);
    graph.addCell(cell1);
  })
  console.log("cell count",graph.getCellCount());

  // let json = toFromJson(obj)
  // useGraph.getState().graph?.fromJSON(json)
  // const model = x6_1.Graph.isGraph(graph) ? graph.model : graph;
  // model.batchUpdate('paste', () => {
  //     model.addCells(this.cells);
  // });
  // useGraph.getState().graph?.center()
}
export const runGraph = (content: string) => {
  const graphJson = useGraph.getState().graph?.toJSON()
  const requestData = {
    "graph": JSON.stringify(graphJson),
    "messages": [
      {
        "content": content,
        "role": "user"
      }
    ]
  }
  fetch("http://192.168.31.231:8071/ai/runAIFlow",
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    }
  ).then(resp => {
    message.open({
      content: '运行中',
      type: 'loading'
    }).then(() => {
      if (resp.status !== 200) {
        message.error('运行失败', 1)
        return
      }
      resp.text().then(_text => {
        console.log("运行完成后的text:", _text);
        message.success('运行完成', 1)
      }).catch(err => {
        console.log(err);
        message.error('运行失败', 1)
      })
    })
  }).catch(err => {
    console.log(err);
    message.error('运行失败', 1)
  })
}

export const clickSend = (content: string) => {

  useChat.getState().addMessage({ content: content, role: "user" })
  useChat.getState().messageLoading()
  //获取value1
  const graphJson = useGraph.getState().graph?.toJSON()
  const requestData = {
    "graph": JSON.stringify(graphJson),
    "messages": [
      {
        "content": content,
        "role": "user"
      }
    ]
  }
  fetch("http://192.168.31.231:8071/ai/runAIFlow",
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    }
  ).then(resp => {
    if (resp.status !== 200) {
      useChat.getState().messageFinish()
      useChat.getState().addMessage({ content: resp.statusText, role: "assistant" })
      return
    }
    resp.text().then(_text => {
      useChat.getState().messageFinish()
      useChat.getState().addMessage({ content: _text, role: "assistant" })
    }).catch(err => {
      console.log(err);
      useChat.getState().messageFinish()
      useChat.getState().addMessage({ content: err, role: "assistant" })
    })
  })
}
